package com.kclmedu.sst.security;

import com.kclmedu.sst.entity.Permission;
import com.kclmedu.sst.entity.User;
import com.kclmedu.sst.mapper.UserMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/*****************************8
 *  自定义认证的凭证来源，我们此处通过  UserDetails 接口来做为来源
 */
public class RBACUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    private static final Logger LOGGER = Logger.getLogger(RBACUserDetailsService.class);

    /*************************
     * 加载用户信息， 通过调用持久层的接口来从DB获取用户及用户的权限
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOGGER.debug("进入 loadUserByUsername()方法，用户名是："+username);
        //1.通过 UserMapper接口来获取用户对象
        User user = userMapper.findByUserName(username);
        LOGGER.info("根据用户名查询到的user对象是："+user);
        if(user != null) {
            LOGGER.debug("用户已查询出来，真实姓名是：" + user.getReal_name());

            //2. 进一步加载用户的权限
            List<Permission> permList = userMapper.findPermissionByUserName(username);
            LOGGER.debug("用户的权限已加载出来，共有：" + permList.size() + " 个权限");
            //3. 把这个查询出来的权限转换成 List<GrantedAuthority>
            //3.1 创建一个新的集合来存放所有权限
            List<GrantedAuthority> authorities = new ArrayList<>();
            //3.2 迭代
            for (Permission perm : permList) {
                GrantedAuthority authority = new SimpleGrantedAuthority(perm.getPerm_tag());
                //添加到集合中
                authorities.add(authority);
            }
            LOGGER.info("权限已转换完成，全部添加到 List<GrantedAuthority>集合中..");
            //4. 把转换出来的集合设置给用户对象
            user.setAuthorities(authorities);
            LOGGER.debug("权限已设置给当前用户：" + user.getUsername());
            //5. 返回这个user实例
            return user;
        } else  {
            LOGGER.warn("用户名不存在....");
            //抛出用户不存在异常
            throw new UsernameNotFoundException("用户不存在");
        }
    }
}
